package com.gx.security.message_digest;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.digests.SHA224Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

/**
 * Created by gx on 2017/3/28.
 */
public class SHAtest {
    private static final String src = "imooc security SHA";

    public static void main(String[] args) {
        jdkSHA1();
        bcSHA1();
        bcSHA224();
        newBcSHA224();
        ccSHA1();
        ccSHA256();
    }

    public static void jdkSHA1() {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA");
            messageDigest.update(src.getBytes());
            String jdkSHA1 = Hex.encodeHexString(messageDigest.digest());
            System.out.println("jdkSHA1:" + jdkSHA1);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }


    public static void bcSHA1() {
        Digest digest = new SHA1Digest();
        digest.update(src.getBytes(), 0, src.length());
        byte[] sha1Bytes = new byte[digest.getDigestSize()];
        //第一个参数 说明输出的目标地
        digest.doFinal(sha1Bytes, 0);
        System.out.println("bc SHA1:" + org.bouncycastle.util.encoders.Hex.toHexString(sha1Bytes));
    }

    public static void bcSHA224() {
        Digest digest = new SHA224Digest();
        digest.update(src.getBytes(), 0, src.length());
        byte[] sha224Bytes = new byte[digest.getDigestSize()];
        //第一个参数 说明输出的目标地
        digest.doFinal(sha224Bytes, 0);
        System.out.println("bc SHA-224:" + org.bouncycastle.util.encoders.Hex.toHexString(sha224Bytes));
    }



    public static void newBcSHA224() {
        try {
            //将BC 的实现加入 加密策略中
            Security.addProvider(new BouncyCastleProvider());
            MessageDigest md = MessageDigest.getInstance("SHA224");
//            MessageDigest md = MessageDigest.getInstance("SHA");
            byte[] md5Bytes = md.digest(src.getBytes());
            //将密文转成16进制
            System.out.println("jdk加入 BC SHA224算法实现:" + Hex.encodeHexString(md5Bytes));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }


    public static void ccSHA1() {
        System.out.println("CC SHA1算法实现:" +    DigestUtils.sha1Hex(src));
    }
//    cc无224  因为cc只是对jdk的封装  jdk本身无 224实现
    public static void ccSHA256() {
        System.out.println("CC SHA256算法实现:" +    DigestUtils.sha256Hex(src));
    }


    }